<template>
<view class="easy-loadimage" :id="uid">
  <block v-if="loadImg&&!isLoadError">
    <image :hidden="!(showImg)" :class="['origin-img',(!openTransition)?'no-transition':'',(showTransition&&openTransition)? 'show-transition':'']" :src="imageSrc" :mode="mode" @load="handleImgLoad" @error="handleImgError"></image>
  </block>
	<block v-else>
		<block v-if="isLoadError">
			<view class="loadfail-img"></view>
		</block>
	</block>
</view>
</template>

<script>

export default {
  data() {
    return {
      uid: '',
      loadImg: false,
      showImg: false,
      isLoadError: false,
      showTransition: false
    };
  },

  components: {},
  props: {
    imageSrc: {
      type: String
    },
    mode: {
      type: String
    },
    scrollTop: {
      type: Number
    },
    openTransition: {
      type: Boolean,
      default: false
    },
    viewHeight: {
      type: Number
    }
  },
  watch: {
    scrollTop(val) {
      this.onScroll(val);
    }

  },

  mounted() {
    this.init();
  },

  methods: {
    init() {
      var that = this;

      function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          let r = Math.random() * 16 | 0,
              v = c == 'x' ? r : r & 0x3 | 0x8;
          return v.toString(16);
        });
      }

      this.setData({
        uid: 'uid-' + generateUUID()
      });
      this.onScroll();
    },

    handleImgLoad(e) {
      var that = this; // console.log('success');

      this.setData({
        showImg: true
      }); // this.$nextTick(function(){
      //     this.showTransition = true
      // })

      setTimeout(() => {
        that.setData({
          showTransition: true
        });
      }, 50);
    },

    handleImgError(e) {
      // console.log('fail');
      this.setData({
        isLoadError: true
      });
    },

    onScroll(scrollTop) {
      var that = this; // 加载ing时才执行滚动监听判断是否可加载

      if (this.loadImg || this.isLoadError) return;
      const id = this.uid;
      this.createSelectorQuery().select('#' + id).boundingClientRect(data => {
        console.log(data);
        if (!data) return;

        if (data.top - this.viewHeight < 0) {
          that.setData({
            loadImg: true
          });
        }

        console.log(this.loadImg);
      }).exec();
    }

  }
};
</script>
<style>
@import "./loadimg.css";
</style>